package jobs;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import common.GranshTask;
import common.Posts;
import common.ReadConfig;
import domain.PostBean;
import domain.WebBean;

public class BootStart {

	/**
	 * 程序入口
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		ExecutorService poll = Executors.newSingleThreadExecutor();
		List<WebBean> webBeans = readConfig();

		for (WebBean webBean : webBeans) {
			String url = webBean.getUrl();
			Map<String, String> users = webBean.getUsers();
			List<String> fids = webBean.getFids();
			for (String fid : fids) {
				// 抓取需要回复的数据
				Future<List<PostBean>> future = poll.submit(new GranshTask(url, fid));
				// 记录发帖成功数 ，如果成功则下一条
				int i = 0;
				for (Entry<String, String> user : users.entrySet()) {
					// 登陆
					Posts post = new Posts(url);
					boolean login = post.login(user.getKey(), user.getValue());
					// 限制每个账号发帖2条
					int index = 3;
					// 如果登陆成功，则开始发帖
					if (login) {
						// 得到fid下的首页的帖子进行发送
						List<PostBean> list = future.get();
						System.out.println("抓取消息：" + list.size());
						for (; i < list.size();) {
							if (index <= 0) {
								System.out.println("账号"+user.getKey()+"，发帖完成");
								break;
							}
							// 开始发帖
							boolean ispost = post.posts(list.get(i));
							// 如果发帖成功，则进行下一个
							if (ispost) {
								i++;
							}
							System.out.println("成功发帖：" + i + "条");
							index--;
						}
					}
				}
				System.out.println("版块：" + fid + "，完成");
			}
			System.out.println("网站：" + url + "，完成");
		}
		poll.shutdown();
	}

	public static List<WebBean> readConfig() throws Exception {
		return ReadConfig.read();
	}
}
